# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *
import logging
import click
from datetime import datetime
from quant.data import juejin

'''
滚IC吃贴水策略
'''

start_date = '2022-01-01'
end_date = str(datetime.now().date())


def init(context):
    schedule(roll, date_rule='1d', time_rule='14:50:00')
    context.confirm = True


def get_ic_position(context):
    pos = [p for p in context.account().positions()
           if p.symbol.startswith('CFFEX.IC')]
    assert len(pos) <= 1
    if len(pos) == 0:
        return None
    return pos[0]


def on_order_status(context, order):
    if order.status == OrderStatus_Rejected:
        logging.error('{}: status: {}, target: {}, error: {}'.format(
            context.now.date(), order.status, order.symbol, order.ord_rej_reason_detail))
        click.confirm('Error')


def roll(context):
    logging.info('****** %s ******' % context.now.date())
    dominant, sub_dominant = juejin.get_dominants(dt)
    logging.info('Current dominant contrct: %s' % dominant)
    zz500 = 'SHSE.000905'
    bars = {bar['symbol']: bar
            for bar in current(symbols=[dominant, zz500])}
    dom_price = bars[dominant]['price']
    index_price = bars[zz500]['price']
    days_to_delist = (get_instrumentinfos(symbols=dominant)[
                      0]['delisted_date'].date() - context.now.date()).days
    p = get_ic_position(context)
    if p is None:
        if dom_price >= index_price:
            logging.info('Dominant contract contango: zz500: {:.1f}, {}: {:.1f}, diff: {:.1f}'.format(
                index_price, dominant, dom_price, dom_price - index_price))
        else:
            if days_to_delist == 0:
                logging.info('Skip open on delisting date')
            else:
                logging.info('Init open: {}, diff: {:.1f}'.format(
                    dominant, dom_price - index_price))
                order_target_volume(
                    symbol=dominant, volume=1, position_side=PositionSide_Long, order_type=OrderType_Market)
                if context.confirm:
                    context.confirm = click.confirm('Continue', default=True)
    else:
        assert p.symbol == dominant
        if days_to_delist == 0:
            logging.info('Close %s' % dominant)
            order_target_volume(
                symbol=dominant, volume=0, position_side=PositionSide_Long, order_type=OrderType_Market)
            logging.info('Open %s' % sub_dominant)
            order_target_volume(
                symbol=sub_dominant, volume=1, position_side=PositionSide_Long, order_type=OrderType_Market)
            if context.confirm:
                context.confirm = click.confirm('Continue', default=True)


def on_backtest_finished(context, indicator):
    print('*' * 50)
    print(indicator)
    zz500 = history(symbol='SHSE.000905', frequency='1d',
                    start_time=start_date, end_time=end_date, df=True)
    print('zz500: {:.2%}'.format(
        zz500.iloc[-1].close / zz500.iloc[0].close - 1))


if __name__ == '__main__':
    '''
        strategy_id策略ID,由系统生成
        filename文件名,请与本文件名保持一致
        mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID,可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    logging.getLogger().setLevel(logging.INFO)
    run(strategy_id='f7396dab-ca82-11ec-b6c3-2a16a8610fe9',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='567120cd2f9b2ce8ae3fbd7ee76ed06bf899b512',
        backtest_start_time='%s 09:00:00' % start_date,
        backtest_end_time='%s 15:00:00' % end_date,
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=1000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)
